﻿using Blog.IRepository;
using EiiF_Blog;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Blog.Repository
{
    public class BaseRepository<TEntity>:SimpleClient<TEntity>, IBaseRepository<TEntity> where TEntity : class, new()
    {
        public BaseRepository(ISqlSugarClient context=null):base(context)
        {
            base.Context = DbScoped.Sugar;
            //建数据库（用一次就行）
            //base.Context.DbMaintenance.CreateDatabase();
            ////建表
            //base.Context.CodeFirst.InitTables(typeof(BlogNews), typeof(Author), typeof(EiiF_Blog.Type));
        }
        public async Task<bool> Create(TEntity tentity)
        {
            return await base.InsertAsync(tentity);
        }

        public async Task<bool> Delete(int Id)
        {
            return await base.DeleteByIdAsync(Id);
        }

        public async Task<bool> Edit(TEntity tentity)
        {
            return await base.UpdateAsync(tentity);
        }

        public virtual async Task<TEntity> Find(int Id)
        {
            return await base.GetByIdAsync(Id);
        }

        public async Task<TEntity> Find(Expression<Func<TEntity, bool>> func)
        {
            return await base.GetSingleAsync(func);
        }

        public virtual async Task<List<TEntity>> Query()
        {
            return await base.GetListAsync();
        }

        public virtual async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> func)
        {
            return await base.GetListAsync(func);
        }

        public virtual async Task<List<TEntity>> Query(int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<TEntity>().ToPageListAsync(page, size, total);
        }

        public virtual async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> func, int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<TEntity>().Where(func).ToPageListAsync(page, size, total);
        }
    }
}
